from django.contrib import auth
from django.core.paginator import Paginator
from rest_framework.authtoken.models import Token
from backend.models import Performance, User, Project, Service, Research, Argument, \
    Achievement
from .util import *


def user_info(request):
    print(request.session.items())
    user_id = request.session.get('user_id')
    user = User.objects.get(id=user_id)
    if not user:
        return format_response(WRONG_POINTER)
    data = {
        "id": user.id,
        "username": user.username,
        "nickname": user.get_full_name(),
        "email": user.email,
        "is_admin": user.is_admin,
        "is_superuser": user.is_superuser,
    }
    return format_response(SUCCESS, data)


def save(request):
    username, password, nickname, email, user_id = format_param(
        request, 'username', 'password', 'nickname', 'email', 'user_id')
    if user_id:
        user = User.objects.get(id=user_id)
        if not user:
            return format_response(WRONG_PARAM)
        try:
            user.username = username
            user.email = email
            user.nickname = nickname
            if password:
                user.set_password(password)
            user.save()
            return format_response(SUCCESS)
        except:
            return format_response(WRONG_PARAM)
    User.objects.create_user(username=username, password=password, nickname=nickname, email=email)
    try:
        return format_response(SUCCESS)
    except:
        return format_response(WRONG_PARAM)


def login(request):
    if request.method == 'POST':
        auth.logout(request)
        data = (json.loads(request.body.decode()))
        username = data['username']
        password = data['password']
        print(username, password)
        try:
            user = auth.authenticate(request, username=username, password=password)
        except:
            return format_response(WRONG_POINTER)

        num = Project.objects.all().filter(head_user_id=user.id, is_active=True).count()
        if num > 0:
            is_admin = True
        else:
            is_admin = False
        if user:
            request.session['is_login'] = True
            request.session['user_id'] = user.id
            request.session['user_name'] = user.username
            request.session['is_admin'] = is_admin
            request.session['is_superuser'] = user.is_superuser
            if user.is_superuser:
                request.session['is_super'] = 1
            auth.login(request, user)
            token, created = Token.objects.get_or_create(user=user)
            data = {
                "id": user.id,
                "username": user.username,
                "nickname": user.get_full_name(),
                "email": user.email,
                "is_admin": is_admin,
                "is_superuser": user.is_superuser,
                "token": token.key,
            }
            return format_response(SUCCESS, data)
        else:
            return format_response(WRONG_POINTER)


def log_out(request):
    auth.logout(request)
    print(request.session.items())
    return format_response(SUCCESS)


def user_list(request):
    page = request.GET.get('page')
    size = request.GET.get('size')

    if request.session.get('is_super'):
        return user_all(request)

    user_id = request.session.get('user_id')
    # projects = Project.objects.all().filter(head_user=user_id)
    # tmp = []
    # for item in projects:
    #     p = Performance.objects.all().filter(project_id=item.id)
    #     for item1 in p:
    #         tmp.append(item1.user)
    #     a = Achievement.objects.all().filter(project_id=item.id)
    #     for item2 in a:
    #         tmp.append(item2.user)
    # users = list(set(tmp))

    user = User.objects.get(id=user_id)

    users = user.get_related_users()

    if len(users) == 0:
        users = User.objects.all().order_by('id')

    total_page = 1
    if page and size:
        paginator = Paginator(users, size)
        total_page = paginator.num_pages
        users = paginator.page(page)

    data = []
    for item in users:
        data.append({
            "id": item.id,
            "username": item.username,
            "nickname": item.get_full_name(),
            "email": item.email,
        })
    result = {
        "list": data,
        "total_page": total_page,
    }
    return format_response(SUCCESS, result)


def user_all(request):
    page = request.GET.get('page')
    size = request.GET.get('size')

    users = User.objects.all().filter(is_active=True, is_superuser=False)

    total_page = 1
    if page and size:
        paginator = Paginator(users, size)
        total_page = paginator.num_pages
        users = paginator.page(page)

    data = []
    for item in users:
        data.append({
            "id": item.id,
            "username": item.username,
            "nickname": item.get_full_name(),
            "email": item.email
        })

    result = {
        "list": data,
        "total_page": total_page,
    }
    return format_response(SUCCESS, result)


def head_users(request):
    users = User.objects.all().filter(is_admin=True)
    print(users)
    data = []
    for item in users:
        data.append({
            "id": item.id,
            "name": item.get_full_name()
        })
    return format_response(SUCCESS, data)


def index(request):
    print(request.session.items())
    if request.session.get('is_super'):
        print("=== is superuser ====")
        size = request.GET.get('size')
        page = request.GET.get('page')
        users = User.objects.all().filter(is_superuser=False)
        paginator = Paginator(users, size)
        total_page = paginator.num_pages
        u = paginator.page(page)
        result = []
        for item in u:
            performance = Performance.objects.all().filter(user_id=item.id)
            total_performance = 0
            for p in performance:
                if p.type == 2:
                    total_performance += p.number
                else:
                    pro = Project.objects.get(id=p.project_id)
                    total_performance += p.number * pro.total_number

            achievement = Achievement.objects.all().filter(user_id=item.id)
            total_achievement = 0
            for p in achievement:
                if p.type == 2:
                    total_achievement += p.number
                else:
                    pro = Project.objects.get(id=p.project_id)
                    total_achievement += p.number * pro.total_number
            argument = Argument.objects.all().filter(user_id=item.id)

            total_argument = 0
            for arg in argument:
                total_argument += arg.get_total_argument()
            print(item.id)
            try:
                service = Service.objects.get(user_id=item.id)
                total_service = service.get_total_service()
            except:
                total_service = 0
            try:
                research = Research.objects.get(user_id=item.id)
                total_research = research.get_total_research()
            except:
                total_research = 0
            total = total_performance + total_achievement + total_argument + total_service + total_research

            result.append({
                "id": item.id,
                "name": item.get_full_name(),
                "performance": total_performance,
                "achievement": total_achievement,
                "argument": total_argument,
                "service": total_service,
                "research": total_research,
                "total": round(total, 2)
            })
        return format_response(SUCCESS, {'total_page': total_page, 'list': result})

    # 普通用户查看自己相关的绩效
    user_id = request.session.get('user_id')
    print(user_id)
    performance = Performance.objects.all().filter(user_id=user_id)
    performance_list = []
    for p in performance:
        pro = p.project
        if p.type == 2:
            number = p.number
        else:
            number = p.number * pro.total_number
        performance_list.append({
            "project": pro.title,
            "number": number,
            "head_user": pro.head_user.get_full_name()
        })

    achievement = Achievement.objects.all().filter(user_id=user_id)
    achievement_list = []
    for p in achievement:
        pro = p.project
        if p.type == 2:
            number = p.number
        else:
            number = p.number * pro.total_number
        achievement_list.append({
            "project": pro.title,
            "number": number,
            "head_user": pro.head_user.get_full_name()
        })

    argument = Argument.objects.all().filter(user_id=user_id)
    argument_list = []
    for arg in argument:
        pro = arg.project
        number = arg.get_total_argument()
        argument_list.append({
            "project": pro.title,
            "number": number,
            "head_user": pro.head_user.get_full_name()
        })

    try:
        service = Service.objects.filter(user_id=user_id).first()
        total_service = {
            "activity_num": service.get_activity_result(),
            "activity": service.activity,
            "hangar_num": service.get_hangar_result(),
            "hangar": service.hangar,
            "visual_design_num": service.get_visual_design_result(),
            "visual_design": service.visual_design,
            "service_num": service.get_service_result(),
            "service": service.service
        }
    except:
        total_service = {
            "activity_num": 0,
            "activity": [],
            "hangar_num": 0,
            "hangar": [],
            "visual_design_num": 0,
            "visual_design": [],
            "service_num": 0,
            "service": []
        }

    try:
        research = Research.objects.filter(user_id=user_id).first()
        total_research = {
            "paper_num": research.get_paper_result(),
            "paper": research.paper,
            "patent_num": research.get_patent_result(),
            "patent": research.patent,
            "award_num": research.get_award_result(),
            "award": research.award,
            "acceptance_num": research.get_acceptance_result(),
            "acceptance": research.acceptance
        }
    except:
        total_research = {
            "paper_num": 0,
            "paper": 0,
            "patent_num": 0,
            "patent": 0,
            "award_num": 0,
            "award": 0,
            "acceptance_num": 0,
            "acceptance": 0
        }

    personal_list = {
        "performance": performance_list,
        "achievement": achievement_list,
        "argument": argument_list,
        "service": total_service,
        "research": total_research
    }

    employee_list = []
    # 负责人查看相关的项目内人员的绩效

    user = User.objects.get(id=request.session.get('user_id'))
    users = user.get_related_users()
    if len(users) > 0:
        projects = Project.objects.all().filter(head_user_id=user_id, is_active=True)
        data = []
        for p in projects:
            user_lists = p.get_user_list()
            for u in user_lists:
                data.append({
                    "user_id": u.id,
                    "project": p.title,
                    "username": u.get_full_name(),
                    "performance": u.get_performamce(p.id),
                    "achievement": u.get_achievement(p.id),
                    "argument": u.get_argument(p.id),
                })
        employee_list = data

    return format_response(SUCCESS, {
        "personal": personal_list,
        "related": employee_list
    })


def user_save_input(request):
    topic, data = format_param(request, 'topic', 'data')
    user_id = request.session.get('user_id')
    # user = User.objects.get(id=user_id)
    print('==== data ====', data.values())
    if 0 in data.values():
        return format_response(WRONG_PARAM, '不能有0哦')
    for item in data.values():
        try:
            float(item)
        except:
            return format_response(WRONG_PARAM)
    num = 0
    # 活动参展
    if topic == 'activity':
        try:
            service = Service.objects.filter(user_id=user_id).first()
            print('========== ', service, ' ==============')
            if not service.activity:
                tmp = [data]
                service.activity = json.dumps(tmp)
                service.save()
            else:
                tmp = json.loads(service.activity)
                tmp.append(data)
                service.activity = json.dumps(tmp)
                service.save()
            print(service.activity)
        except:
            tmp = [data]
            service = Service(
                user_id=user_id,
                activity=json.dumps(tmp)
            )
            service.save()
        num = service.get_activity_result()

    # 机库讲解
    if topic == 'hangar':
        try:
            service = Service.objects.filter(user_id=user_id).first()
            if not service.hangar:
                tmp = [data]
                service.hangar = json.dumps(tmp)
                service.save()
            else:
                tmp = json.loads(service.hangar)
                tmp.append(data)
                service.hangar = json.dumps(tmp)
                service.save()
            print(service.hangar)
        except:
            tmp = [data]
            service = Service(
                user_id=user_id,
                hangar=json.dumps(tmp)
            )
            service.save()
        num = service.get_hangar_result()

    # 视觉设计
    if topic == 'visual_design':
        try:
            service = Service.objects.filter(user_id=user_id).first()
            if not service.visual_design:
                tmp = [data]
                service.visual_design = json.dumps(tmp)
                service.save()
            else:
                tmp = json.loads(service.visual_design)
                tmp.append(data)
                service.visual_design = json.dumps(tmp)
                service.save()
            print(service.visual_design)
        except:
            tmp = [data]
            service = Service(
                user_id=user_id,
                visual_design=json.dumps(tmp)
            )
            service.save()
        num = service.get_visual_design_result()

    # 综合服务
    if topic == 'service':
        try:
            service = Service.objects.filter(user_id=user_id).first()
            if not service.service:
                tmp = [data]
                service.service = json.dumps(tmp)
                service.save()
            else:
                tmp = json.loads(service.service)
                print('============', tmp, '===============')
                tmp.append(data)
                service.service = json.dumps(tmp)
                service.save()
            print(service.service)
        except:
            tmp = [data]
            service = Service(
                user_id=user_id,
                service=json.dumps(tmp)
            )
            service.save()
        num = service.get_service_result()

    # 论文
    if topic == 'paper':
        try:
            research = Research.objects.filter(user_id=user_id).first()
            if not research.paper:
                tmp = [data]
                research.paper = json.dumps(tmp)
                research.save()
            else:
                tmp = json.loads(research.paper)
                tmp.append(data)
                research.paper = json.dumps(tmp)
                research.save()
            print(research.paper)
        except:
            tmp = [data]
            research = Research(
                user_id=user_id,
                paper=json.dumps(tmp)
            )
            research.save()
        num = research.get_paper_result()
    # 专利软著
    if topic == 'patent':
        try:
            research = Research.objects.filter(user_id=user_id).first()
            if not research.patent:
                tmp = [data]
                research.patent = json.dumps(tmp)
                research.save()
            else:
                tmp = json.loads(research.patent)
                tmp.append(data)
                research.patent = json.dumps(tmp)
                research.save()
            print(research.patent)
        except:
            tmp = [data]
            research = Research(
                user_id=user_id,
                patent=json.dumps(tmp)
            )
            research.save()
        num = research.get_patent_result()

    # 奖项
    if topic == 'award':
        try:
            research = Research.objects.filter(user_id=user_id).first()
            if not research.award:
                tmp = [data]
                research.award = json.dumps(tmp)
                research.save()
            else:
                tmp = json.loads(research.award)
                tmp.append(data)
                research.award = json.dumps(tmp)
                research.save()
            print(research.award)
        except:
            tmp = [data]
            research = Research(
                user_id=user_id,
                award=json.dumps(tmp)
            )
            research.save()
        num = research.get_award_result()

    # acceptance
    if topic == 'acceptance':
        try:
            research = Research.objects.filter(user_id=user_id).first()
            if not research.acceptance:
                tmp = [data]
                research.acceptance = json.dumps(tmp)
                research.save()
            else:
                tmp = json.loads(research.acceptance)
                tmp.append(data)
                research.acceptance = json.dumps(tmp)
                research.save()
            print(research.paper)
        except:
            tmp = [data]
            research = Research(
                user_id=user_id,
                acceptance=json.dumps(tmp)
            )
            research.save()
        num = research.get_acceptance_result()
    print(topic, type(data), data)
    return format_response(SUCCESS, num)
